package com.opdar.athena.web.interceptors;

import com.opdar.athena.base.RedisSessionManager;
import com.opdar.athena.entities.UserEntity;
import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.base.Interceptor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.IOException;

/**
 * Created by shiju on 2017/1/24.
 */
public class AuthViewInterceptor implements Interceptor,ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public boolean before() {
        String tokrn = (String) Context.getRequest().getSession().getAttribute("token");
        if(tokrn == null){
            tokrn = Context.getRequest().getParameter("token");
            Context.getRequest().getSession().setAttribute("token",tokrn);
        }
        if(tokrn != null){
            RedisSessionManager sessionManager = applicationContext.getBean(RedisSessionManager.class);
            UserEntity user = sessionManager.get(tokrn);
            if(user != null){
                sessionManager.clearTimeout(tokrn);
                Context.putAttribute("user",user);
                return true;
            }
        }
        try {
            Context.getResponse().sendRedirect("/login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean after() {
        return true;
    }

    @Override
    public void finish() {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
